<template>
  <div>
    <el-form ref="form" :rules="rules" :model="form" label-width="120px" :disabled="ifDisable" v-loading="loading">
      <el-row v-if="type =='add' || type =='edit'">
        <el-col :span="12">
          <el-form-item label="所属仓库" prop="warehouseCode">
            <warehouseSelect ref="warehouseSelect"  @setWarehouseCode="setWarehouseCode" style="width: 100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  label="入驻商" prop="shipmentCode" >
            <shipmentSelect3 ref="shipmentSelect3"  @setShipmentInfo="setShipmentInfo" style="width: 100%"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="type =='view'">
        <el-col :span="12">
          <el-form-item label="所属仓库">
            <el-input v-model="form.warehouseName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  label="入驻商">
            <el-input v-model="form.shipmentName" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="生效日期" prop="gmtEffective">
            <el-date-picker
              style="width:100%"
              v-model="form.gmtEffective"
              type="date"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">

          <el-form-item label="失效日期" prop="gmtIneffective">
            <el-date-picker
              style="width:100%"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"

              v-model="form.gmtIneffective"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合同号" prop="contractNo">
            <el-input v-model="form.contractNo"  placeholder="请输入合同号" maxlength="30" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="仓储费类型" prop="storageFeeType">
            <el-select v-model="form.storageFeeType" placeholder="请选择仓储费类型" @change="changeStorageFeeType" clearable  style="width:100%">
              <el-option
                v-for="item in storageFeeData"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="最小计费量" prop="minBillingVolume" v-if="form.storageFeeType == 'SCATTERED'">
            <el-input v-model="form.minBillingVolume"  placeholder="请输入最小计费量" maxlength="30" />
          </el-form-item>
        </el-col>

        <el-col :span="12"  v-if="form.storageFeeType == 'WHOLE'">
          <el-form-item label="开始计费日期" prop="gmtBillingBegin">
            <el-date-picker
              style="width:100%"
              v-model="form.gmtBillingBegin"
              type="date"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="计费周期" prop="billingCycle">
            <el-select v-model="form.billingCycle" placeholder="请选择计费周期" clearable style="width:100%">
              <el-option value="1" label="1" />
              <el-option value="3" label="3"/>
              <el-option value="5" label="5"/>
              <el-option value="7" label="7"/>
              <el-option value="15" label="15"/>
              <el-option value="30" label="30"/>
              <el-option value="180" label="180"/>
              <el-option value="360" label="360"/>

            </el-select>

          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" v-if="form.storageFeeType == ''">
          <el-form-item label="计费单位" prop="billingUnit">
            <el-select v-model="form.billingUnit" placeholder="请选择计费单位  " clearable  style="width:100%">
              <el-option
                v-for="item in billingData"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.storageFeeType == 'WHOLE'" >
          <el-form-item label="计费单位" prop="billingUnit">
            <el-select v-model="form.billingUnit" placeholder="请选择计费单位  " style="width:100%">
              <el-option
                v-for="item in billingWHOLEData"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.storageFeeType == 'SCATTERED'">
          <el-form-item label="计费单位" prop="billingUnit">
            <el-select v-model="form.billingUnit" placeholder="请选择计费单位  " style="width:100%">
              <el-option
                v-for="item in billingSCATTEREDData"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="单价" prop="unitPrice">
            <el-input v-model="form.unitPrice" placeholder="请输入单价" maxlength="21"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="数量" prop="quantity"   v-if="form.storageFeeType == 'WHOLE'">
            <el-input v-model="form.quantity" placeholder="请输入数量" maxlength="21"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="总金额" prop="amountMoney"   v-if="form.storageFeeType == 'WHOLE'" >
            <el-input v-model="form.amountMoney" placeholder="请输入总金额" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="form.remarks" placeholder="请输入备注" maxlength="100"/>
          </el-form-item>
        </el-col>
      </el-row>



        <el-row>
          <el-col :span="24">
            <el-form-item label="上传附件">
              <el-upload
                ref="upload"
                class="upload-demo"
                :action="uploadUrl"
                :limit="1"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-upload="beforeUploadFile"
                :on-error="handleError"
                :auto-upload="true"
                :headers="getAuthorization()"
                :on-success="handleAvatarSuccess"
                :file-list="fileList"
              >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传1个文件，且不超过10M</div>
              </el-upload>
              <el-input v-model="form.attachmentName" type="hidden" />

              <el-input v-model="form.attachmentUrl" type="hidden" />
            </el-form-item>
          </el-col>
        </el-row>
    </el-form>
    <el-button type="primary" @click="url"  :disabled="isDisable" plain style="margin-top:-10%;margin-left:10%">查看上传文件</el-button>

  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
import VXETablePluginElement from 'vxe-table-plugin-element'
import 'vxe-table-plugin-element/dist/style.css'
import shipmentSelect3 from '@/views/components/shipmentSelect3.vue'
import warehouseSelect from '@/views/components/warehouseSelect.vue'
import { contractAdd ,contractActive,contractUnActive,contractDelete,contractDetail} from '@/api/basicInfo'
import {getWarehouse} from '@/api/basicInfo'

Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
VXETable.use(VXETablePluginElement)

export default {
  name: "ShipmentAdd",
  components: {
    warehouseSelect,
    shipmentSelect3,
  },
  props: ["type", "index"],

  watch: {
    // 'form.storageFeeType': {
    //   handler () {
    //     this.form.billingUnit = '',
    //     this.form.gmtBillingBegin = '',
    //     this.form.quantity = ''
    //     this.form.amountMoney = ''
    //     this.form.minBillingVolume = ''
    //   },
    //   deep: true
    // },
    'form.quantity': {
      handler () {
        this.form.amountMoney = parseFloat((this.form.quantity * this.form.unitPrice).toFixed(6))
      },
      deep: true
    },
    'form.unitPrice': {
      handler () {
        this.form.amountMoney = parseFloat((this.form.quantity * this.form.unitPrice).toFixed(6))
      },
      deep: true
    },

  },
  computed: {
    ifDisable() {
      // 查看 表单全部禁用
      return this.type == "view";
    },
    isDisable(){
      if(this.form.attachmentUrl){
        return false;
      }else{
        return true;
      }
    }
  },
  data() {
    return {
        uploadUrl: this.uploadUrl,
        uploadComplete:true,
        warehouseData:[],
        loading: false,
        isWatch:'false',
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
        fileList: [],
        storageFeeData:[
          { code: "WHOLE", name: "包仓" },
          { code: "SCATTERED",name: "零仓" },
        ],
        billingWHOLEData:[
          { code: "LOCATION", name: "库位" },
          { code: "AREA",name: "面积" },
        ],
        billingSCATTEREDData:[
          { code: "PIECE", name: "件" },
          { code: "TON",name: "吨" },
          { code: "LOCATION", name: "库位" },
        ],
        billingData:[],
      form: {
        shipmentCode: '',
        warehouseCode:"",
        attachmentUrl:'',
        billingUnit:'',
        attachmentName:'',
        storageFeeType:'',
        contractOperationCostList:'',
        minBillingVolume:'',
        contractNo:'',
        gmtBillingBegin:'',
        gmtEffective:'',
        gmtIneffective:'',
        billingCycle:'',
        unitPrice:'',
        quantity:'',
        amountMoney:'',
        remarks:''
      },
      rules: {
        shipmentCode: [
          { required: true, message: '请选择入驻商', trigger: 'change' }
        ],
        warehouseCode: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        contractNo: [
          { required: true, message: '请输入合同号', trigger: 'change' },
          // { pattern: /^[1-9]+[0-9]*$/, message: '合同号为正整数' }

        ],
        unitPrice:[
            { pattern: /^\d{0,14}(\.\d{0,6})?$/, message: '单价需大于0，小数点前限制14位小数点后限制6位' }
        ],
        quantity:[
            { pattern: /^\d{0,14}(\.\d{0,6})?$/, message: '数量需大于0，小数点前限制14位小数点后限制6位' }
        ],
        minBillingVolume:[
            { pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, message: '最小计费量必须大于0' }
        ],
        gmtBillingBegin: [
          { required: true, message: '请选择开始计费日期', trigger: 'change' }
        ],
        gmtEffective: [
          { required: true, message: '请选择生效日期', trigger: 'change' }
        ],
        gmtIneffective: [
          { required: true, message: '请选择失效日期', trigger: 'change' }
        ],
        storageFeeType: [
          { required: true, message: '请选择仓储费类型', trigger: 'change' }
        ],
        billingCycle: [
          { required: true, message: '请选择计费周期', trigger: 'change' }
        ],


      },
    };
  },
  created() {
    this.getWarehouse()
    console.log(Date.now())
  },

  methods: {
    changeStorageFeeType(e){
      console.log(e)
      if(e == 'SCATTERED'){
        this.form.billingUnit = '',
        this.form.gmtBillingBegin = ''
        this.form.quantity = ''
        this.form.amountMoney = ''

      }
      if(e == 'WHOLE'){
        this.form.minBillingVolume = ''
        this.form.billingUnit = ''
      }

        // this.form.billingUnit = '',
        // this.form.gmtBillingBegin = '',
        // this.form.quantity = ''
        // this.form.amountMoney = ''
        // this.form.minBillingVolume = ''
    },
    //查看上传文件
    url(){
      let url = this.form.attachmentUrl
      window.open(url,'_blank');
    },
    //仓库查询
    getWarehouse(){
      this.loading = true
      getWarehouse().then(response => {
        this.warehouseData = response.data
        this.loading = false
        this.getInfo();

      })
    },
    // 获取页面信息
    getInfo() {
      this.fileList = []

      let code = this.$route.query.code ? this.$route.query.code : "";
      if(this.type == 'view' || this.type == 'edit'){
        this.loading = true
        if(this.index == 'purchase'){

          contractDetail(code).then(response => {
            this.form = response.data,
            this.tableData = this.form.contractOperationCostList
            let arr = {}
            arr.name = response.data.attachmentName
            arr.url = response.data.attachmentUrl
            if(arr.name || arr.url){
              this.fileList.push(arr)
            }


            this.loading = false
            this.$refs.warehouseSelect.setSelectValue(this.form.shipmentCode, this.form.warehouseCode);
            this.$refs.shipmentSelect3.setSelectValue(this.form.warehouseCode, this.form.shipmentCode);

          }).catch(() => this.loading = false)
        }
        if(this.index == 'sale'){
          saleDetail(code).then(response => {
          })
        }
      }
    },

    // 选择入驻商
    setShipmentInfo(info) {
      this.form.shipmentCode = info.partyCode;
      this.form.shipmentName = info.userName;
    },
    // 选择仓库
    setWarehouseCode(value){
      this.form.warehouseCode = value;

    },

      //上传前校验
      beforeUploadFile(file) {
        let extension = file.name.substring(file.name.lastIndexOf('.')+1)
        let size = file.size / 1024 / 1024

        // if(extension !== 'xls') {
        //   this.$message.error("只能上传xls,xlsx的文件")
        // }
        if(size > 10) {
          this.$message.error('上传文件大小不能超过 10MB!')
            return false;
        }
        this.uploadComplete=false;
      },

      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },

    handleUpload(raw) {
      this.files.push(raw.file);
    },
    // 选择客户
    setCustomerCode(value) {
      this.form.shipmentName = value.name
      this.form.shipmentCode = value;
      this.tableData = [];
    },

    handleRemove(file, fileList) {
        if(fileList.length<1){
            this.form.attachmentUrl='';
        }
    },
    handlePreview(file) {
      // console.log(file)
    },
    handleAvatarSuccess(response, file, fileList) {
      // console.log(file)
      this.$message({ message: response.msg, type: 'success' });
      this.form.attachmentUrl = response.data;
      this.form.attachmentName = file.name;
      this.uploadComplete=true;
      this.$refs['form'].validateField('attachmentUrl');
      // console.log(fileList)
    },
      // 文件上传失败时的钩子
      handleError(err, file, fileList) {
        this.$notify.error({
          title: '错误',
          message: `文件上传失败`
        });
        this.uploadComplete=true;
      },

    uploadFile:function(file){
        this.fileData.append('file', file.file);
    },

    },
};
</script>
<style scoped>
.custom-grid {
  display: inline-block;
  font-size: 14px;
  color: #8c939d;
  margin-right: 20px;
}
.avatar-uploader /deep/.el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon {
  box-sizing: border-box;
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border-width: 1px;
  border-style: dashed;
  border-color: #c0ccda;
}
.avatar-uploader-icon:hover {
  border-color: #409eff;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.el-cascader {
  width: 100%;
}
</style>
